import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 vuex 的 store 模块
import store from '@/store'

// 导入需要的路由组件
// import Reg from '@/views/Reg.vue'
const Reg = () => import('@/views/Reg.vue')
// import Login from '@/views/Login.vue'
const Login = () => import('@/views/Login.vue')
// import Main from '@/views/Main.vue'
const Main = () => import('@/views/Main.vue')
// import Home from '@/views/Menus/Home.vue'
const Home = () => import('@/views/Menus/Home.vue')
// import UserInfo from '@/views/Menus/User/Info.vue'
const UserInfo = () => import('@/views/Menus/User/Info.vue')
// import UserAvatar from '@/views/Menus/User/Avatar.vue'
const UserAvatar = () => import('@/views/Menus/User/Avatar.vue')
// import UserPwd from '@/views/Menus/User/Pwd.vue'
const UserPwd = () => import('@/views/Menus/User/Pwd.vue')
// 导入分类的列表页面
// import CateList from '@/views/Menus/Article/List.vue'
const CateList = () => import('@/views/Menus/Article/List.vue')
// 导入文章的列表页面
// import ArticleList from '@/views/Menus/Article/ArtList.vue'
const ArticleList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  // 路由规则的数组
  routes: [
    // 注册页面的路由规则
    { path: '/reg', component: Reg },
    // 登录页面的路由规则
    { path: '/login', component: Login },
    // 后台主页的路由规则
    {
      path: '/',
      component: Main,
      redirect: '/home',
      children: [
        // 子路由规则
        // path: '/home' 是完整的写法“父+子”
        // path: 'home' 是简写形式，把父 path 给省略了，而且子路由的 path 不能以 / 开头
        { path: 'home', component: Home },
        { path: 'user-info', component: UserInfo },
        { path: 'user-avatar', component: UserAvatar },
        { path: 'user-pwd', component: UserPwd },
        { path: 'art-cate', component: CateList },
        { path: 'art-list', component: ArticleList }
      ]
    }
    // 处理页面找不到的情况
    // { path: '*', component: NotFound }
  ]
})

// 声明全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    // 不需要访问权限，直接放行
    next()
  } else {
    // 需要访问权限，需要判断 token 啦
    // 技术难点：在这个位置，怎么拿到 vuex 中的 token 呢？
    const token = store.state.user.token
    if (token) {
      // token 有值，直接放行
      next()
    } else {
      // 没有 token，则强制跳转到登录页面
      next('/login')
    }
  }
})

export default router
